package sandbox;

import helpers.d;
import soenudp.Command;
import soenudp.UDPHelper;
import soenudp.UDPMessage;
import soenudp.UDPException;

public class UDPViewGMSRecv extends Thread
{
  final int PORT = 20000;   // Server port where people can reach me.
  String MTL_View = "\n";   // A String contain the view. Could be a 
  String TOR_View = "\n";   // Hash Map, Table, List, Dictionary...
  
  public UDPViewGMSRecv(String MTL_View, String TOR_View) 
  {
    this.MTL_View = MTL_View;
    this.TOR_View = TOR_View;
  }

  public void run()
  {
    UDPHelper unicastHelper = new UDPHelper();
    try 
    {  
      // Can be used to send and receive, but in this example
      // I'm using it to read the a PONG request over unicast.
      unicastHelper.startUnicastServer("GMS001", PORT);
      UDPMessage request;   
      
      while ( (request = unicastHelper.getMessage()) != null )
      {
        int       fromPort  = request.recv_from_port;
        String    fromIP    = request.recv_from_ip;
        String    optioText = request.op_text; //in case you need more...
        Command   command   = request.command;
        
        switch(command)
        {
          case PONG:
           //d.out("PONG From IP: " + fromIP + " PORT: " + fromPort + " NodeID: " + optioText);
            synchronized(MTL_View)
            {
              MTL_View += optioText + ":" + fromIP + ":" + fromPort  + "\n";
            }
            break;
          
          /*case XYZ:*/
          
          // I can also reply directly within this thread using sendToNode(fromIP, fromPort ...)
          // If I was a leader I would probably handle the request from my front-end in here,
          // and re-broadcast them to my replicas... using a 2nd instance of UDPHelper
            
          default: // Should not really end up here...
            d.out("Received " + command +  " From IP: " + fromIP + 
                " PORT: " + fromPort + " Optional value: " + optioText);
            break;
            
        }
        if (isInterrupted()) {
            d.out("dfgdfgd");
            unicastHelper.stopUnicast();
            break;
        }
            
      }
      // unicastHelper.stopUnicast();
    } 
    catch (UDPException e) 
    {
      e.printStackTrace();
    }
  }

  public synchronized String getMTLView() 
  {
    return this.MTL_View;
  }
  
  public synchronized void clearAllViews() 
  {
    this.MTL_View = "";
    this.TOR_View = "";
  }
}
